#include <unistd.h>
#include <pthread.h>
#include "ThreadLinux.h"

ThreadRunReturn __stdcall threadFunction(void * object)
{
   Thread * thread = (Thread *) object;
   thread->run(thread->param);
   pthread_exit(NULL);
   return  (void *)0;
}

Thread::Thread(ThreadRun _run)
{
   started = false;
   detached = false;
   run = _run;
}

Thread::~Thread()
{
   stop();
}

int Thread::start(void* pra)
{
   if (!started)
   {
	   param = pra;
	   if (pthread_create(&threadHandle,NULL, threadFunction, this) == 0)
	   {
			started = true;
			if (detached)
			{
				pthread_detach(threadHandle);
			}
			else
			{
				
			}
		   
	   }
   }
   return started;
}

//wait for current thread to end.
DWORD Thread::join()
{
   DWORD status = (DWORD) NULL;
   if (started && !detached)
   {
	   pthread_join(threadHandle,(void **)&status);
   }

   return status;
}

void Thread::detach()
{
   if (started && !detached)
   {
		pthread_detach(threadHandle);
   }
   detached = true;
}

void Thread::stop()
{
   if (started && !detached)
   {
	   pthread_cancel(threadHandle);
   }
}

void Thread::sleep(unsigned int delay)
{
   usleep(delay*1000);
}

int Thread::createLock(ThreadLockType *lock) {
	return pthread_mutex_init(lock, NULL);	
}
int Thread::lock(ThreadLockType *lock) {
	return pthread_mutex_lock(lock);
}
int Thread::tryLock(ThreadLockType *lock) {
	return pthread_mutex_trylock(lock);
}
int Thread::unlock(ThreadLockType *lock) {
	return pthread_mutex_unlock(lock);
}
int Thread::destoryLock(ThreadLockType *lock) {
	return pthread_mutex_destroy(lock);
}
